<template>
  <a-card>
    <div class="operator">
      <a-button @click="addNew" type="primary">新建</a-button>
    </div>

    <a-table
      bordered
      :columns="columns"
      :data-source="dataSource"
      :loading="spinning"
      @change="handleTableChange"
      :pagination="pagination"
    >
      <div slot="action" slot-scope="record">

        <a v-if="record.Menu_ParentID == 0" style="margin-right: 8px" @click="addChildrenNew(record)">
          <a-icon type="plus" />添加
        </a>

        <a style="margin-right: 8px" @click="editRole(record)">
          <a-icon type="edit" />编辑
        </a>

        <a @click="deleteRecord(record)"> <a-icon type="delete" />删除 </a>

      </div>

      <!-- <p slot="expandedRowRender" slot-scope="record" style="margin: 0">
              <pre>{{ record }}</pre>
            </p> -->
    </a-table>

    <a-drawer
      :title="drawertitle"
      :width="600"
      :visible="visible"
      :body-style="{ paddingBottom: '80px' }"
      @close="onClose"
    >
      <a-form :form="form" layout="vertical" @submit="handleSubmit">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="菜单名称">
              <a-input
                v-decorator="[
                  'Menu_Name',
                  {
                    rules: [
                      { required: true, message: 'Please enter menu name' },
                    ],
                  },
                ]"
                placeholder="Please enter menu name"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="14">
            <a-form-item label="菜单路由">
              <a-input
                v-decorator="[
                  'Menu_Url',
                  {
                    rules: [
                      {
                        required: true,
                        message: 'Please enter menu url',
                      },
                    ],
                  },
                ]"
                :rows="4"
                placeholder="please enter menu url"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="14">
            <a-form-item label="排序">
              <a-input
                v-decorator="[
                  'Menu_Num',
                  {
                    rules: [
                      {
                        required: true,
                        message: 'Please enter menu num',
                      },
                    ],
                  },
                ]"
                :rows="4"
                placeholder="please enter menu num"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <div
          :style="{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
            zIndex: 1,
          }"
        >
          <a-button :style="{ marginRight: '8px' }" @click="onClose">
            Cancel
          </a-button>
          <a-button type="primary" html-type="submit">
            Submit
          </a-button>
        </div>
      </a-form>
    </a-drawer>
  </a-card>
</template>

<script>

const columns = [
  {
    title: "编号",
    dataIndex: "Menu_ID",
  },
  {
    title: "排序",
    dataIndex: "Menu_Num",
    sorter: true
  },
  {
    title: "菜单名称",
    dataIndex: "Menu_Name",
  },
  {
    title: "菜单路由",
    dataIndex: "Menu_Url",
  },
  {
    title: "创建时间",
    dataIndex: "Menu_CreateTime",
    sorter: true
  },
  {
    title: "操作",
    scopedSlots: { customRender: "action" },
  },
];

export default {

  data() {
    return {
      advanced: true,

      visible: false,
      selectRow: null,
      isEdit: false,

      dataSource: [],

      form: this.$form.createForm(this),
      drawertitle: "添加菜单",

      spinning: false,
      pagination: {
        total: 20,
        title: "",
        tableName: "",
      },
      columns: columns,
    };
  },

  created: function() {
    this.loadTable("iToolBase", "Sys_Menu");
  },

  methods: {

    deleteRecord(row) {
      console.log(row);
      var that = this;
      this.$confirm({
        title: "Are you sure delete this menu?",
        content: "删除后将从菜单列表中移除",
        okText: "Yes",
        okType: "danger",
        cancelText: "No",
        onOk() {
          that.$cloud
            .invokeApiJson(
              "iToolBase",
              JSON.stringify({
                Sys_Menu: {
                  Menu_ID: row.Menu_ID,
                },
              }),
              "remove"
            )
            .then((res) => {
              res = typeof res == "string" ? JSON.parse(res) : res;
              console.log(res);
              if (res.code == 200) {
                that.$message.success("删除成功");

                var isParent = that.dataSource.filter(item => item.Menu_ID == row.Menu_ID).length > 0;

                if (isParent) {
                  that.dataSource = that.dataSource.filter(
                    (item) => item.Menu_ID !== row.Menu_ID
                  );
                } else {
                  that.dataSource = that.dataSource.filter(
                    (item) => {
                      item.children = item.children.filter(itemChildren => itemChildren.Menu_ID !== row.Menu_ID);
                      return true;
                    }
                  );
                }
                

              } else {
                that.$message.error("发生错误：" + res.info);
              }
            })
            .catch((error) => {
              console.log(error);
              that.$message.error("发生错误：" + error);
            });
        },
        onCancel() {},
      });
    },

    handleTableChange(p, filters, sorter) {
      console.log(p, filters, sorter);
      this.loadTable(
        this.pagination.title,
        this.pagination.tableName,
        p.current,
        sorter.field,
        (sorter.order || "").replace("end", "")
      );
    },

    addNew() {
      this.drawertitle = "添加菜单";
      this.visible = true;
      this.isEdit = false;
      this.selectRow = null;

      setTimeout(
        function() {
          this.form.setFieldsValue({
            Menu_Name: "",
            Menu_Url: "",
            Menu_Num: 0
          });
        }.bind(this),
        200
      );
    },

    editRole(row) {
      this.selectRow = row;
      this.isEdit = true;

      this.drawertitle = "编辑菜单";
      this.visible = true;
      setTimeout(
        function() {
          this.form.setFieldsValue({
            Menu_Name: row.Menu_Name,
            Menu_Url: row.Menu_Url,
            Menu_Num: row.Menu_Num
          });
        }.bind(this),
        200
      );
    },

    addChildrenNew(row){
      console.log(row)
      this.selectRow = row;
      this.isEdit = false;

      this.drawertitle = `添加 "${row.Menu_Name}" 子菜单`;
      this.visible = true;
      setTimeout(
        function() {
          this.form.setFieldsValue({
            Menu_Name: '',
            Menu_Url: '',
            Menu_Num: 0
          });
        }.bind(this),
        200
      );
    },

    onClose() {
      this.visible = false;
      this.selectRow = null;
    },

    handleSubmit(e) {
      e.preventDefault();
      var that = this;
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log("Received values of form: ", values);

          var isAddChildren = that.isEdit == false & that.selectRow != null;

          var where = {
            Sys_Menu: {
              Menu_Name: values.Menu_Name,
              Menu_Url: values.Menu_Url,
              Menu_Num: values.Menu_Num
            },
          };

          if (that.selectRow != null) {
            if(isAddChildren) {
              where.Sys_Menu.Menu_ParentID = that.selectRow.Menu_ID;
            } else {
              where.Sys_Menu.Menu_ID = that.selectRow.Menu_ID;
            }
          }

          if (that.selectRow == null) {
            where.Sys_Menu.Menu_ParentID = 0;
          }

          if(that.selectRow == null || isAddChildren){
            where.Sys_Menu.Menu_IsShow = 1;
            where.Sys_Menu.Menu_CreateTime = new Date().Format(
              "yyyy-MM-dd HH:mm:ss"
            );
          }

          console.log(where);

          that.$cloud
            .invokeApiJson(
              "iToolBase",
              JSON.stringify(where),
              this.selectRow == null ? "register" : (isAddChildren ? "register" : "modify")
            )
            .then((res) => {
              console.log(res);
              res = typeof res == "string" ? JSON.parse(res) : res;

              if (res.code == 200) {
                if (this.selectRow == null) {
                  that.dataSource.push({
                    key: res.Sys_Menu.date,
                    Menu_ID: res.Sys_Menu.date,
                    Menu_Num: values.Menu_Num,
                    Menu_Name: values.Menu_Name,
                    Menu_Url: values.Menu_Url,
                    Menu_ParentID: 0,
                    Menu_CreateTime: new Date().Format("yyyy-MM-dd HH:mm:ss"),
                    children: []
                  });
                } else if(isAddChildren) {
                  for (let index = 0; index <  that.dataSource.length; index++) {
                    const element =  that.dataSource[index];
                    if (element.Menu_ID == that.selectRow.Menu_ID) {
                      element.children.push({
                        key: res.Sys_Menu.date,
                        Menu_ID: res.Sys_Menu.date,
                        Menu_Num: values.Menu_Num,
                        Menu_Name: values.Menu_Name,
                        Menu_Url: values.Menu_Url,
                        Menu_ParentID: that.selectRow.Menu_ID,
                        Menu_CreateTime: new Date().Format("yyyy-MM-dd HH:mm:ss")
                      });
                    }
                  }
                } 
                else if(that.selectRow.Menu_ParentID > 0) {
                  for (let index = 0; index < that.dataSource.length; index++) {
                    const element = that.dataSource[index];
                    if (element.Menu_ID == that.selectRow.Menu_ParentID) {
                      for (let indexChildren = 0; indexChildren < element.children.length; indexChildren++) {
                        const elementChildren = element.children[indexChildren];
                        if (elementChildren.Menu_ID == that.selectRow.Menu_ID) {
                          elementChildren.Menu_Name = values.Menu_Name;
                          elementChildren.Menu_Url = values.Menu_Url;
                          elementChildren.Menu_Num = values.Menu_Num;
                        }
                      }
                    }
                  }
                }
                else {
                  for (let index = 0; index < that.dataSource.length; index++) {
                    const element = that.dataSource[index];
                    if (element.Menu_ID == that.selectRow.Menu_ID) {
                      element.Menu_Name = values.Menu_Name;
                      element.Menu_Url = values.Menu_Url;
                      element.Menu_Num = values.Menu_Num;
                    }
                  }
                }

                that.$message.success(
                  this.selectRow == null ? "添加成功" : "修改成功"
                );
              } else {
                that.$message.error("发生错误：" + res.msg);
              }
              that.onClose();
            })
            .catch((error) => {
              that.$message.error("发生错误：" + error);
              console.log(error);
            });
        }
      });
    },

    loadTable(title, tableName, page, field, orderby) {
      this.spinning = true;

      this.pagination.title = title;
      this.pagination.tableName = tableName;

      var script = {};

      script["[]"] = {
        count: 100,
        page: page ? page : 1,
        query: 2,
      };

      script["[]"][tableName] = {};

      if (field) {
        script["[]"][tableName]["@order"] =
          orderby == "asc" ? field + "+" : field + "-";
      }

      script["total@"] = "/[]/total";

      this.$cloud
        .invokeApiJson("iToolBase", JSON.stringify(script), "get")
        .then((res) => {
          var data = JSON.parse(res);
          this.spinning = false;
          var tableData = data["[]"];
          this.dataSource = [];

          this.pagination.total = data.total;
          this.pagination["show-total"] = (total, range) =>
            `${range[0]}-${range[1]} of ${total} items`;
          this.pagination["pageSize"] = 100;
          this.pagination["defaultCurrent"] = 1;

          for (let index = 0; index < tableData.length; index++) {
            const row = tableData[index];
            row[tableName].key = row[tableName].Menu_ID;
            if ((row[tableName].Menu_ParentID - 0) < 1) {
              row[tableName].Menu_ParentID = 0;
              row[tableName].children = [];
              this.dataSource.push(row[tableName]);
            }
          }


          for (let index = 0; index < tableData.length; index++) {
            const row = tableData[index];
            if (row[tableName].Menu_ParentID > 0) {
              for (let index = 0; index < this.dataSource.length; index++) {
                const element = this.dataSource[index];
                if(row[tableName].Menu_ParentID == element.Menu_ID)
                  element.children.push(row[tableName]);
              }
            }
          }

          console.log(this.dataSource);
        });
    },
  },
};
</script>

<style lang="less" scoped>
.search {
  margin-bottom: 54px;
}
.fold {
  width: calc(100% - 216px);
  display: inline-block;
}
.operator {
  margin-bottom: 18px;
}

.operator button {
  margin-right: 18px;
}

@media screen and (max-width: 900px) {
  .fold {
    width: 100%;
  }
}
</style>
